package com.ruoyi.report.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.docx.DocxFmtConvert;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.onlyoffice.domain.OnFile;
import com.ruoyi.onlyoffice.service.IOnFileService;
import com.ruoyi.report.domain.ReportTemplateModel;
import com.ruoyi.report.service.IReportTemplateModelService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 报告模板模型Controller
 * 
 * @author luguanqing
 * @date 2020-11-30
 */
@Api(value="报告模板模型",tags = "报告模板模型接口")
@RestController
@RequestMapping("/report/model")
public class ReportTemplateModelController extends BaseController
{
    @Autowired
    private IReportTemplateModelService reportTemplateModelService;

    @Autowired
    private IOnFileService iOnFileService;

    /**
     * 查询报告模板模型列表
     */
    @ApiOperation(value="报告模板列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "pageNum", value = "页数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "pageSize", value = "每页记录数", required = true, dataType = "String"),
    })
    @GetMapping("/list")
    public TableDataInfo list(ReportTemplateModel reportTemplateModel)
    {
        startPage();
        List<ReportTemplateModel> list = reportTemplateModelService.selectReportTemplateModelList(reportTemplateModel);
        for(ReportTemplateModel r : list) {
            //获取最新版本数据
            OnFile onFile = iOnFileService.selectNewVersion(r.getId());
            r.setOnFile(onFile);
        }
        return getDataTable(list);
    }

    /**
     * 文件上传
     */
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String fileName = FileUploadUtils.upload(RuoYiConfig.getTemPath(), file, false);
            if(StringUtils.isNotEmpty(fileName)){
                AjaxResult ajax = AjaxResult.success();
                ajax.put("fileName", fileName);
                return ajax;
            }
        }
        return AjaxResult.error("上传文件异常，请联系管理员");

    }

    /**
     * 报告直接上传
     */
    @Log(title = "报告直接上传", businessType = BusinessType.INSERT)
    @PostMapping("/uploadReport")
    public AjaxResult uploadReport(MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String fileName = FileUploadUtils.upload(RuoYiConfig.getTemPath(), file, false);
            if(StringUtils.isNotEmpty(fileName)){
                AjaxResult ajax = AjaxResult.success();
                String profile =  RuoYiConfig.getProfile();
                ajax.put("fileName", fileName);
                //上传到onlyoffice服务器
                FileUtils fileUtils = new FileUtils();
                fileUtils.copyFile(StringUtils.replace(fileName, "/profile", profile), RuoYiConfig.getOoFile() + StringUtils.substring(fileName, fileName.lastIndexOf("/") + 1, fileName.length()));
                return ajax;
            }
        }
        return AjaxResult.error("上传文件异常，请联系管理员");

    }


    /**
     * 导出报告模板模型列表
     */
    //@PreAuthorize("@ss.hasPermi('system:model:export')")
    @Log(title = "报告模板模型", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ReportTemplateModel reportTemplateModel)
    {
        List<ReportTemplateModel> list = reportTemplateModelService.selectReportTemplateModelList(reportTemplateModel);
        ExcelUtil<ReportTemplateModel> util = new ExcelUtil<ReportTemplateModel>(ReportTemplateModel.class);
        return util.exportExcel(list, "model");
    }

    /**
     * 获取报告模板模型详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:model:query')")
    @ApiOperation(value="报告模板模型详情")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@ApiParam(name="id",value="报告模板id",required=true)@PathVariable("id") String id)
    {
        return AjaxResult.success(reportTemplateModelService.selectReportTemplateModelById(id));
    }

    /**
     * 新增报告模板模型
     */
    @ApiOperation(value="新增报告模板")
    @Log(title = "报告模板模型", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@ApiParam(name="报告模板对象",value="传入json格式",required=true) @RequestBody ReportTemplateModel reportTemplateModel) throws Exception {
        String modelId = IdUtils.fastSimpleUUID();
        reportTemplateModel.setId(modelId);
        String profile = RuoYiConfig.getProfile();
        //上传时间
        reportTemplateModel.setUploadtime(DateUtils.getNowDate());
        //将当前文件保存到onlyoffice服务器地址下
        FileUtils fileUtils = new FileUtils();
        //获取报告内容地址
        String content = reportTemplateModel.getContentAddress();
        String contentAdress = reportTemplateModel.getContentAddress();
        try {
            //doc文件
            if(StringUtils.equals("doc",  StringUtils.substring(content, content.indexOf(".") + 1, content.length()))){
                //替换为docx文件，路径不变
                reportTemplateModel.setContentAddress(content + "x");
                //内容路径
                content = StringUtils.replace(content, "/profile", profile);
                DocxFmtConvert.convertDocFmt(content, 12);
                content = content + "x";
                contentAdress = contentAdress + "x";
            }else if(StringUtils.equals("xls",  StringUtils.substring(content, content.indexOf(".") + 1, content.length()))){
                //替换为xlsx文件，路径不变
                reportTemplateModel.setContentAddress(content + "x");
                //内容路径
                content = StringUtils.replace(content, "/profile", profile);
                DocxFmtConvert.convertXlsfmt(content.replaceAll("/", "\\\\"), 51);
                content = content + "x";
                contentAdress = contentAdress + "x";
            }else{
                //内容路径
                content = StringUtils.replace(content, "/profile", profile);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //模板保存
        int ret = reportTemplateModelService.insertReportTemplateModel(reportTemplateModel);
        if(ret > 0) {
            //保存成功后添加记录到历史oo列表中
            OnFile onFile = new OnFile();
            onFile.setFileId(IdUtils.fastSimpleUUID());
            onFile.setFileName(reportTemplateModel.getTemplateName() + StringUtils.substring(contentAdress, contentAdress.indexOf(".")));
            onFile.setFileType(StringUtils.substring(contentAdress, contentAdress.indexOf(".") + 1));
            onFile.setVersion("1.0.0");
            onFile.setCreatedTimes(DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS));
            onFile.setUserId(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
            onFile.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
            onFile.setReportId(modelId);
            onFile.setFileSize(reportTemplateModel.getFileSize());
            iOnFileService.insertOnFile(onFile);
            //将当前文件保存到onlyoffice服务器地址下
            fileUtils.copyFile(content, RuoYiConfig.getOoFile() +"\\"+onFile.getFileId()+"."+onFile.getFileType());
        }
        return toAjax(ret);
    }

    /**
     * 修改报告模板模型
     */
    @ApiOperation(value="修改报告模板")
    @Log(title = "报告模板模型", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@ApiParam(name="报告模板对象",value="传入json格式",required=true) @RequestBody ReportTemplateModel reportTemplateModel) throws IOException {
        int ret = reportTemplateModelService.updateReportTemplateModel(reportTemplateModel);
        if(ret > 0) {
            //变更历史版本新增
            reportTemplateModel = reportTemplateModelService.selectReportTemplateModelById(reportTemplateModel.getId());
            //保存成功后添加记录到历史oo列表中
            OnFile onFile = new OnFile();
            String fileName = IdUtils.fastSimpleUUID();
            onFile.setFileId(fileName);
            onFile.setFileName(StringUtils.substring(reportTemplateModel.getContentAddress(), reportTemplateModel.getContentAddress().lastIndexOf("/") + 1, reportTemplateModel.getContentAddress().length()));
            onFile.setFileType(StringUtils.substring(reportTemplateModel.getContentAddress(), reportTemplateModel.getContentAddress().indexOf(".") + 1));
            String maxVersion = iOnFileService.selectMaxVersion(reportTemplateModel.getId());
            if(null == maxVersion) {
                maxVersion = "1.0.0";
            }else {
                String[] split = maxVersion.split("\\.");
                maxVersion = split[0]+"."+split[1]+"."+ (Integer.valueOf(split[2])+1);
            }
            onFile.setVersion(maxVersion);
            onFile.setCreatedTimes(DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS));
            onFile.setUserId(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
            onFile.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
            onFile.setReportId(reportTemplateModel.getId());
            iOnFileService.insertOnFile(onFile);
            //将当前文件保存到onlyoffice服务器地址下
            FileUtils fileUtils = new FileUtils();
            String profile = RuoYiConfig.getProfile();
            //内容路径
            String contentAddress = StringUtils.replace(reportTemplateModel.getContentAddress(), "/profile", profile);
            fileUtils.copyFile(contentAddress, RuoYiConfig.getOoFile() + fileName + StringUtils.substring(contentAddress, contentAddress.indexOf(".")));
        }
        return toAjax(ret);
    }

    /**
     * 删除报告模板模型
     */
    @ApiOperation(value="删除报告模板")
    @Log(title = "报告模板模型", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@ApiParam(name="id",value="报告模板ids",required=true)@PathVariable String[] ids)
    {
        return toAjax(reportTemplateModelService.deleteReportTemplateModelByIds(ids));
    }
}
